<template>
    <rx-dialog @handOk="onOk" @cancel="cancel">
        <div class="pre-container">
            <div class="pre-header-toolbar">
                <a-radio-group v-model="localPermssion.type">
                    <a-radio value="field">{{i18n('easy','简易模式')}}</a-radio>
                    <a-radio value="script">{{i18n('Advanced','高级模式')}}</a-radio>
                </a-radio-group>
            </div>
            <a-tabs :activeKey="localPermssion.type"  @change="changeType" >
                <a-tab-pane key="field"  force-render>
                    <RxConditionGroup ref="table" :level="2" :ruleData="conditionConfig" :defaultRule="defaultRule">
                        <template slot="conditionDiv" slot-scope="{rule,setValid}">
                            <div class="rx-condition-row" >
                                <div>
                                    <!--              字段                      -->
                                    <a-tooltip placement="top">
                                        <span slot="title" class="numeric-input-title">{{$comi18('listDef.field', '字段')}}</span>
                                        <a-select style="width: 100%" :options="fields" v-model="rule.field" @change="changeField(rule)"/>
                                    </a-tooltip>
                                </div>
                                <div>
                                    <!--              操作符                      -->
                                    <a-tooltip placement="top">
                                        <span slot="title" class="numeric-input-title">{{i18n('form.operator','操作符')}}</span>
                                        <a-select style="width: 100%" :options="getOperators(rule.datatype)" v-model="rule.operator" ></a-select>
                                    </a-tooltip>
                                </div>
                                <div>
                                    <!--              值类型                      -->
                                    <a-tooltip placement="top">
                                        <span slot="title" class="numeric-input-title">{{i18n('form.valueType','值类型')}}</span>
                                        <a-select style="width: 100%" :options="getValOptions(rule.datatype)" v-model="rule.valType" @change="valueTypeChange($event,rule)"></a-select>
                                    </a-tooltip>
                                </div>
                                <div>
                                    <!--              值                      -->
                                    <a-tooltip placement="top">
                                        <span slot="title" class="numeric-input-title">{{$comi18('listDef.val', '值')}}</span>
                                        <template  v-if="rule.valType==='field'">
                                            <template v-if="rule.operator==='between'">
                                                <rx-between-field
                                                    v-model="rule.val"
                                                    :start-options="fields"
                                                    :end-options="fields">
                                                </rx-between-field>
                                            </template>
                                            <template v-else>
                                                <a-select :options="fields" v-model="rule.val" style="width: 100%;"></a-select>
                                            </template>

                                        </template>
                                        <template v-else-if="rule.valType==='group'" >
                                            <rx-group-component v-model="rule.val" :single="rule.operator==='='" :showDimId="true"></rx-group-component>
                                        </template>
                                        <template v-else-if="rule.valType==='user'" >
                                            <rx-user-component v-model="rule.val" :single="rule.operator==='='"></rx-user-component>
                                        </template>
                                        <template v-else-if="rule.valType==='context'">
                                            <a-select style="width: 100%" :options="contexts" v-model="rule.val"></a-select>
                                        </template>
                                        <template v-else-if="rule.valType==='dialog'">
                                            <a-input-group compact style="display:flex;">
                                                <a-input v-model="rule.val" style="flex: 1;" allowClear></a-input>
                                                <a-button @click="dialogSelect(rule)" style="padding: 0 8px;background-color: #f5f7fa;">
                                                    <my-icon type="iconVue3_setting"></my-icon>
                                                </a-button>
                                            </a-input-group>
                                        </template>
                                        <template v-else>
                                            <template  v-if="rule.datatype==='date'">
                                                <template v-if="rule.operator==='between'">
                                                    <rx-between-date v-model="rule.val"></rx-between-date>
                                                </template>
                                                <template v-else>
                                                    <rx-form-date v-model="rule.val"></rx-form-date>
                                                </template>
                                            </template>
                                            <template v-else>
                                                <template v-if="rule.operator==='between'">
                                                    <rx-between v-model="rule.val"> </rx-between>
                                                </template>
                                                <template v-else>
                                                    <a-input v-model="rule.val"></a-input>
                                                </template>
                                            </template>
                                        </template>
                                    </a-tooltip>

                                </div>
                            </div>
                        </template>
                    </RxConditionGroup>
                </a-tab-pane>
                <a-tab-pane key="script"  force-render>
                    <rx-monaco-editor
                        ref="script"
                        v-model="localPermssion.script"
                        language="javascript"
                        style="height: 400px "
                    >
                        <template v-slot:monacoeditor>
                            <div>
                                {{i18n('list.selectFields','选择字段')}}: <a-select style="width: 200px" :options="fields"   @change="insertCode" ></a-select>
                            </div>
                        </template>
                    </rx-monaco-editor>

                </a-tab-pane>

            </a-tabs>
        </div>
    </rx-dialog>
</template>

<script>
import RxBetween from "./rxBetween";
import {RxUserComponent,RxGroupComponent,Util,RxMonacoEditor,RxConditionGroup} from "@lowcode/jpaas-common-lib";
import RxBetweenField from "./rxBetweenField";
import RxBetweenDate from "./rxBetweenDate";
import RxFormDate from "./rxFormDate";
import ActionDialog from "./ActionDialog.vue";
export default {
    name: "actionPermission",
    components: {
        RxBetweenField,
        RxBetween,
        RxUserComponent,
        RxMonacoEditor,
        RxGroupComponent,
        RxBetweenDate,
        RxFormDate,
        RxConditionGroup
    },
    props:{
        srcFields:{
            type:Array,
            default:[]
        },
        permission:{
            type:String,
            default: "{type:\"\",setting:[],script:\"\"}",
        },
        layerid: {
            type: String,
            default: ""
        },
        destroy: {
            type: Function
        }
    },
    computed: {
        table() {
            return this.$refs.table;
        },
    },
    data(){
        return {
            conditionConfig: {
                condition: "AND",
                rules: [],
            },
            defaultRule:{
                field:'',
                logic:'',
                operator:'',
                valType:'',
                val:''
            },
            columns:[
                {title: this.$comi18('listDef.field', '字段'), dataIndex: 'field',scopedSlots: {customRender: 'field'},width:100},
                {title: this.i18n('form.loginSymbol','逻辑符'), dataIndex: 'logic', scopedSlots: {customRender: 'logic'},width:80},
                {title: this.i18n('form.operator','操作符'), dataIndex: 'operator', scopedSlots: {customRender: 'operator'},width:100},
                {title: this.i18n('form.valueType','值类型'), dataIndex: 'valType',  scopedSlots: {customRender: 'valType'},width:100},
                {title: this.$comi18('listDef.val', '值'), dataIndex: 'val', scopedSlots: {customRender: 'val'},width:150}
            ],
            valTypeOptions:[],
            logicOptions:[{label:this.i18n('form.and','与'),value:"and"},{label:this.i18n('form.or','或'),value:"or"}],
            valTypes:[
                {label:this.i18n('form.fixValue','固定值'),value:"fixed",needVal:true,type:['string','date','number']},
                {label:this.i18n('form.userGroup','用户组'),value:"group",needVal:true,type:['string']},
                {label:this.i18n('form.user','用户'),value:"user",needVal:true,type:['string']},
                {label:this.i18n('context','上下文'),value:"context",needVal:true,type:['string']},

                {label:this.i18n('form.today','今天'),value:"today",needVal:true,type:['date']},
                /* {label:this.i18n('dialog','对话框'),value:"dialog",needVal:true,type:['string']},*/
            ],
            localPermssion:{},
            fields:[],

            /*type表示选项在什么类型的数据里面展示*/
            operatorType:[
                {label:this.i18n('eq','等于'),value:"=",type:['string','number','date']},
                {label:this.i18n('noeq','不等于'),value:"!=",type:['string']},
                {label:this.i18n('include','包含'),value:"contains",type:['string']},
                {label:this.i18n('includeIn','包含于'),value:"includeIn",type:['string']},
                {label:this.i18n('notInclude','不包含'),value:"notcontains",type:['string']},

                {label:this.i18n('overtake','大于'),value:">",type:['number','date']},
                {label:this.i18n('geq','大于等于'),value:">=",type:['number','date']},
                {label:this.i18n('under','小于'),value:"<",type:['number','date']},
                {label:this.i18n('leq','小于等于'),value:"<=",type:['number','date']},
                {label:this.i18n('between','介于'),value:"between",type:['number','date']}
            ],
            contexts:[
                {label:this.i18n('form.currentUserID','当前用户ID'),value:"curUserId",needVal:false,type:['string']},
                {label:this.i18n('form.groupID','当前用户组ID'),value:"curGroupId",needVal:false,type:['string']}
            ]
        }
    },
    created(){
        this.init();
    },
    methods:{
        dialogSelect(rule){
            Util.open({
                curVm:this,
                widthHeight:['600px','400px'],
                component:ActionDialog,
                data:{
                    dialogData:rule.dialogData || {}
                }
            },(action,data)=>{
                if(action){
                    rule.dialogData = {...data}
                    rule.val = data.fieldVal ;
                }
            })
        },
        valueTypeChange(val,rule){
            if(['group','user'].includes(val)){
                rule.val = []
            }else {
                rule.val = ''
            }
        },
        i18n(name,text,key){
            return this.$ti18(name,text,"formCellRender",key);
        },
        init(){
            for(var i=0;i<this.srcFields.length;i++){
                var o=this.srcFields[i];
                if(!o.key){
                    continue;
                }
                this.fields.push(o);
            }
            var find = this.fields.find((item) =>item.value== "CREATE_BY_");
            if(!find){
                this.addCommonFields();
            }

            //数据权限
            this.localPermssion=JSON.parse(this.permission);
            // 简易模式回显内容
            this.conditionConfig = this.localPermssion.setting;
        },
        addCommonFields(){
            var createBy={label:this.$ti18('rxForm.createBy','创建人'),value:"CREATE_BY_",key:"string"};
            var updateBy={label:this.i18n('form.updateBy','更新人'),value:"UPDATE_BY_",key:"string"};
            var createTime={label:this.$ti18("rxForm.createTime","创建时间"),value:"CREATE_TIME_",key:"date"};
            var updTime={label:this.$ti18('rxForm.updateTime','更新时间'),value:"UPDATE_TIME_",key:"date"};

            this.fields.push(createBy);
            this.fields.push(updateBy);
            this.fields.push(createTime);
            this.fields.push(updTime);
        },
        addRow() {
            var obj={field:"", operator: '', valType: '',val:"",datatype:""};
            this.table.addRow(obj);
        },
        removeRow() {
            this.table.removeRows();
        },
        upRow() {
            this.table.moveUp();
        },
        downRow() {
            this.table.moveDown();
        },
        cancel(){
            Util.closeWindow(this,"cancel");
        },
        onOk(vm){
            if(this.localPermssion.type=="field"){
                this.localPermssion.script="";
                this.localPermssion.setting=this.table.getData();
                if(this.localPermssion.setting.rules.length==0){
                    this.$message.error('请配置规则');
                    vm.loading = false;
                    return
                }
            }
            else{
                this.localPermssion.setting=[];
                if(!this.localPermssion.script){
                    this.$message.error('请配置规则');
                    vm.loading = false;
                    return;
                }
            }
            var json=JSON.stringify(this.localPermssion);
            Util.closeWindow(this,"ok",json);
        },

        getOperators(type){
            if(!type){
                return [];
            }
            return this.operatorType.filter(item=>item.type.includes(type))
        },
        getValOptions(type){
            if(!type){
                return [];
            }
            return this.valTypes.filter(item=>item.type.includes(type))
        },

        changeField(record){
            let type="string";
            let o = this.fields.find(item=>item.value === record.field);
            if(o){
                type = o.key;
            }
            record.datatype = type;
        },
        changeType(type){
            this.localPermssion.type=type;
        },
        insertCode(field){
            this.$refs.script.insertContent("record."+field);
        }


    }

}
</script>

<style scoped>
.pre-header-toolbar{
    padding:0 0 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 42px;
}
.table-operator{
    text-align: right;
    width:100%;
}
.pre-container{
    height: 100%;
    display: grid;
    grid-template-rows: auto 1fr;
}
.pre-container >>> .ant-tabs-top-bar{
    display: none;
}
.rx-condition-row{
    display: grid;
    gap: 0 10px;
    grid-template-columns: repeat(3,1fr) minmax(220px,1fr);
    min-height: 34px;
}
</style>